﻿using Biz;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace App
{
    public partial class FrmQLSanPham : Form
    {
        private Category _cats;
        private Manufacturer _manufactures;
        private List<Product> _products;
        private List<Property> _props;

        public FrmQLSanPham()
        {
            InitializeComponent();

            _cats = new Category();
            _manufactures = new Manufacturer();
        }

        private void FrmQLSanPham_Load(object sender, EventArgs e)
        {
            CbCategories.DataSource = _cats.GetAll();
            CbManufacturers.DataSource = _manufactures.GetAll();

            ReloadList();
        }

        private void ReloadList()
        {
            lstDSSP.Items.Clear();
            _products = (new Product()).GetAll();
            foreach (var p in _products)
            {
                AddProductToList(p);
            }
        }
        private void AddProductToList(Product p)
        {
            ListViewItem lvi = new ListViewItem(p.Name);
            lvi.SubItems.Add(new ListViewItem.ListViewSubItem(lvi, p.CurrentPrice.ToString()));
            lvi.SubItems.Add(new ListViewItem.ListViewSubItem(lvi, p.Category.ToString()));
            lvi.SubItems.Add(new ListViewItem.ListViewSubItem(lvi, p.Manufacturer.ToString()));

            lstDSSP.Items.Add(lvi);
        }

        private void ReloadPropertiesList()
        {
            _props = Property.GetByCategory((Category) CbCategories.SelectedItem);
            if (_props != null)
            {
                LstProperties.Items.Clear();
                foreach (var pr in _props)
                {
                    ListViewItem lvi = new ListViewItem(pr.Name);
                    if (lstDSSP.SelectedItems.Count > 0) {
                        lvi.SubItems.Add(new ListViewItem.ListViewSubItem(lvi, ProductProperties.GetValue(pr, _products[lstDSSP.SelectedItems[0].Index])));
                    } else {
                        lvi.SubItems.Add(new ListViewItem.ListViewSubItem());
                    }

                    LstProperties.Items.Add(lvi);
                }
            }
        }

        private void SetProductInfo(Product p)
        {
            TxtTenSP.Text = p.Name;
            TxtGiaSP.Text = p.CurrentPrice.ToString();

            foreach (var it in CbCategories.Items)
            {
                if (it.ToString().Equals(p.Category.ToString()))
                {
                    CbCategories.SelectedItem = it;
                    break;
                }
            }

            foreach (var mf in CbManufacturers.Items)
            {
                if (mf.ToString().Equals(p.Manufacturer.ToString()))
                {
                    CbManufacturers.SelectedItem = mf;
                    break;
                }
            }

            ChkFeatured.Checked = (p.IsFeatured ? true : false);
            TxtShortDesc.Text = p.ShortDescription;
            TxtDesc.Text = p.Description;

            ReloadPropertiesList();

            LstImages.Items.Clear();
            foreach (var f in ProductImage.GetImagesOf(p))
            {
                LstImages.Items.Add(f);
            }
        }

        private void lstDSSP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstDSSP.SelectedItems.Count > 0)
            {
                SetProductInfo(_products[lstDSSP.SelectedItems[0].Index]);
            }
        }

        private void BtnBrowser_Click(object sender, EventArgs e)
        {
            ofd.ShowDialog();
            TxtImgPath.Text = ofd.FileName;
        }

        private void BtnAddImage_Click(object sender, EventArgs e)
        {
            LstImages.Items.Add(TxtImgPath.Text);
        }

        ListViewItem.ListViewSubItem SelectedLSI;
        private void LstProperties_MouseUp(object sender, MouseEventArgs e)
        {
            ListViewHitTestInfo i = LstProperties.HitTest(e.X, e.Y);

            if (i == null || i.Item == null || i.SubItem == null || i.SubItem == i.Item.SubItems[0]) return;

            SelectedLSI = i.SubItem;
            if (SelectedLSI == null)
                return;

            int border = 0;
            switch (LstProperties.BorderStyle)
            {
                case BorderStyle.FixedSingle:
                    border = 1;
                    break;
                case BorderStyle.Fixed3D:
                    border = 2;
                    break;
            }

            int CellWidth = SelectedLSI.Bounds.Width;
            int CellHeight = SelectedLSI.Bounds.Height;
            int CellLeft = border + LstProperties.Left + i.SubItem.Bounds.Left;
            int CellTop = LstProperties.Top + i.SubItem.Bounds.Top;
            // First Column
            if (i.SubItem == i.Item.SubItems[0])
                CellWidth = LstProperties.Columns[0].Width;

            txtEdit.Location = new Point(CellLeft, CellTop);
            txtEdit.Size = new Size(CellWidth, CellHeight);
            txtEdit.Visible = true;
            txtEdit.BringToFront();
            txtEdit.Text = i.SubItem.Text;
            txtEdit.Select();
            txtEdit.SelectAll();
        }

        private void HideTextEditor()
        {
            txtEdit.Visible = false;
            if (SelectedLSI != null)
                SelectedLSI.Text = txtEdit.Text;
            SelectedLSI = null;
            txtEdit.Text = "";
        }

        private void LstProperties_MouseDown(object sender, MouseEventArgs e)
        {
            HideTextEditor();
        }

        private void txtEdit_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
                HideTextEditor();
        }

        private void txtEdit_Leave(object sender, EventArgs e)
        {
            HideTextEditor();
        }

        private void BtnThem_Click(object sender, EventArgs e)
        {
            /* Product p = new Product();
            p.Name = TxtTenSP.Text;
            p.CurrentPrice = Int32.Parse(TxtGiaSP.Text);
            p.ShortDescription = TxtShortDesc.Text;
            p.Description = TxtDesc.Text;
            p.IsFeatured = ChkFeatured.Checked;
            p.IsDeleted = false;
            p.Category = (Category) CbCategories.SelectedItem;
            p.Manufacturer = (Manufacturer)CbManufacturers.SelectedItem;
            
            List<string> imgs = new List<string>();
            foreach (var it in LstImages.Items)
            {
                if (it.ToString().Contains(':'))
                {
                    File.Copy(it.ToString(), @"C:\Users\Nguyên\Documents\Visual Studio 2013\Projects\Webshop-sgu\Web\Images\Products\" + Path.GetFileName(it.ToString()));
                    imgs.Add(Path.GetFileName(it.ToString()));
                }
            }

            List<KeyValuePair<Property, string>> props = new List<KeyValuePair<Property, string>>();
            if (_props != null)
            {
                for (int i = 0; i < _props.Count; ++i)
                {
                    props.Add(new KeyValuePair<Property, string>(_props[i], LstProperties.Items[i].SubItems[1].Text));
                }
            } */
            try
            {
                Product p = new Product();
                List<string> imgs = new List<string>();
                List<KeyValuePair<Property, string>> props = new List<KeyValuePair<Property, string>>();

                GetProductInfo(p, imgs, props);
                Product.AddNew(p, imgs, props);
                ReloadList();
            }
            catch
            {
                return;
            }
        }

        private void CbCategories_SelectedIndexChanged(object sender, EventArgs e)
        {
            ReloadPropertiesList();
        }

        private void BtnXoa_Click(object sender, EventArgs e)
        {
            if (lstDSSP.SelectedItems.Count > 0)
            {
                Product.Delete(_products[lstDSSP.SelectedItems[0].Index]);
            }

            ReloadList();
        }

        private void GetProductInfo(Product p, List<string> imgs, List<KeyValuePair<Property, string>> props)
        {
            //Product p = new Product();
            p.Name = TxtTenSP.Text;
            p.CurrentPrice = Int32.Parse(TxtGiaSP.Text);
            p.ShortDescription = TxtShortDesc.Text;
            p.Description = TxtDesc.Text;
            p.IsFeatured = ChkFeatured.Checked;
            p.IsDeleted = false;
            p.Category = (Category)CbCategories.SelectedItem;
            p.Manufacturer = (Manufacturer)CbManufacturers.SelectedItem;

            //List<string> imgs = new List<string>();
            foreach (var it in LstImages.Items)
            {
                if (it.ToString().Contains(':'))
                {
                    string path = @"G:\SGU\Xay Dung Phan Mem\code\Web\Images\Products\" + Path.GetFileName(it.ToString());

                    if (!File.Exists(path))
                        File.Copy(it.ToString(), path);

                    imgs.Add(Path.GetFileName(it.ToString()));
                }
                else
                {
                    imgs.Add(it.ToString());
                }
            }

            //List<KeyValuePair<Property, string>> props = new List<KeyValuePair<Property, string>>();
            if (_props != null)
            {
                for (int i = 0; i < _props.Count; ++i)
                {
                    props.Add(new KeyValuePair<Property, string>(_props[i], LstProperties.Items[i].SubItems[1].Text));
                }
            }
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            if (lstDSSP.SelectedItems.Count <= 0)
            {
                MessageBox.Show(this.Parent, "Chọn một sản phẩm trước khi xóa nó!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Product p = new Product();
            List<string> imgs = new List<string>();
            List<KeyValuePair<Property, string>> props = new List<KeyValuePair<Property, string>>();

            GetProductInfo(p, imgs, props);

            Product.Update(_products[lstDSSP.SelectedItems[0].Index], p, imgs, props);
            ReloadList();
        }
    }
}
